let callbacks = []

const loadScriptAsync = (src, cb) => {
    const existScript = document.getElementById(src)
    const callback = cb || function () {}
    if (!existScript) {
        const script = document.createElement('script')
        script.src = src
        script.id = src
        document.body.appendChild(script)
        callbacks.push(callback)
        const onEnd = stdOnEnd
        onEnd(script)
    }
    function stdOnEnd(script) {
        script.onload = function() {
            // this.onload = null here is necessary
            // because even IE9 works not like others
            this.onerror = this.onload = null
            for (const cb of callbacks) {
                cb(null, script)
            }
            callbacks = null
        }
        script.onerror = function() {
            this.onerror = this.onload = null
            cb(new Error('Failed to load ' + src), script)
        }
    }
}
export default loadScriptAsync